﻿/*****************************
 * Author: YanNI
 * Create：2017/7/6 9:06:26
 * Email:  admin@ircove.com
 * QQ:     401608886
 * TEl: 13520446271
 ****************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VF.Ip
{
    /// <summary>
    /// 节点
    /// </summary>
    internal class Node
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="b"></param>
        public Node(byte b)
        {
            this.v = b;
        }
        public byte v;
        public List<Node> child = new List<Node>(256);
        public Node AddChild(byte b)
        {
            var node = child.Find(x => x.v == b);
            if (node == null)
            {
                node = new Node(b);
                child.Add(node);
            }
            return node;
        }
        public int pos = -1;
        /// <summary>
        /// 获取相近的的节点
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        internal Tuple<bool, Node> findsim(byte b)
        {
            int i = (child.Count * b) / 255;

            byte t = child[i].v;
            if (t == b)
            {
                return Tuple.Create(true, child[i]);
            }
            else if (t > b)
            {
                while (--i >= 0)
                {
                    t = child[i].v;
                    if (t == b)
                    {
                        return Tuple.Create(true, child[i]);
                    }
                    else if (t < b)
                    {
                        return Tuple.Create(false, child[i]);
                    }
                }
            }
            else
            {
                while (++i < child.Count)
                {
                    t = child[i].v;
                    if (t == b)
                    {
                        return Tuple.Create(true, child[i]);
                    }
                    else if (t > b)
                    {
                        if (i > 0) i--;
                        return Tuple.Create(false, child[i]);
                    }
                }
            }
            return Tuple.Create(false, child[0]);
        }
    }
}
